﻿using FictionsDownload.DAL;
using FictionsDownload.Model;
using FictionsDownload.Static;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FictionsDownload.BLL
{
    class WebFormat : BaseBLL
    {
        public bool Add(WebFormatModel webFormat)
        {
            //WebFormat数据校验
            if (webFormat.Name == "" || webFormat.Name == null)
            {
                Message = "名称为空";
                return false;
            }
            if (webFormat.Url == "" || webFormat.Url == null)
            {
                Message = "Url为空";
                return false;
            }
            //数据库重复查询
            if (FindByName(webFormat.Name) == null)
            {
                if (FindByUrl(webFormat.Url) == null)
                {
                    dal.Insert(webFormat);
                    Message = "添加成功";
                    return true;
                }
                else
                {
                    Message = "已有URL";
                    return false;
                }
            }
            else
            {
                Message = "已有名称";
                return false;
            }
        }
        public void Delete(WebFormatModel webFormat)
        {
            webFormat.Delete(dal);
        }
        public bool Update(WebFormatModel webFormat)
        {
            //WebFormat数据校验
            if (webFormat.Name == "" || webFormat.Name == null)
            {
                Message = "名称为空";
                return false;
            }
            if (webFormat.Url == "" || webFormat.Url == null)
            {
                Message = "Url为空";
                return false;
            }
            webFormat.ActiveTime = DateTime.Now;
            dal.Update(webFormat);
            Message = "修改成功";
            return true;
        }
        public WebFormatModel FindByName(string name)
        {
            return Get<WebFormatModel>(w => w.Name == name);
        }
        public WebFormatModel FindByUrl(string url)
        {
            return Get<WebFormatModel>(w => w.Url == url);
        }
        /// <summary>
        /// 通过URL查找WebFormat
        /// </summary>
        /// <param name="selectUrl"></param>
        /// <returns></returns>
        public WebFormatModel FindByUrlDns(string selectUrl)
        {
            WebFormatModel webFormat = Get<WebFormatModel>(w => w.Url == selectUrl);
            if (webFormat == null)
            {
                //去除http和https的差异，用主网址再找一次
                var webFormats = GetList<WebFormatModel>();
                foreach (var item in webFormats)
                {
                    if (item.Url.UrlDnsEquals(selectUrl))
                    {
                        webFormat = Get<WebFormatModel>(w => w.Id == item.Id);
                        break;
                    }
                }
            }
            return webFormat;
        }
    }
}
